#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
A module for finding scattering directions of a max on a givven density grid.
'''
import sys
from optparse import OptionParser

from plane import Plane
from grid_plane import PlaneGrid
import fr_parser
import fr_scatdir_module
from readdensity import readdensity


optparser= OptionParser()   
optparser.add_option('-d', dest='dfile',
					help='File name of the density grid')
options, args = optparser.parse_args(sys.argv[1:])
# Parse the density grid file
density, size, max_density_val = None, None, None
if options.dfile:
	density, size, max_density_val = readdensity(options.dfile)

# prepare grid for searching max
grid = PlaneGrid(incr=[int(size), int(size)])
for pl in density:        
    grid.add(plane=Plane(pl[0], pl[1]), val=pl[2])
density_grid = grid.returnGrid()						

# Parsig of a maximums
lines = sys.stdin.read().split('\n')
maxs = []
for line in lines:
    val = fr_parser.parse_line(line)
    if val: maxs.append(val)    
# Processing each max 
for m in maxs:
    mplane = Plane(int(m[0]), int(m[1])).normal() # plane of maximum
    data = fr_scatdir_module.return_plot(grid, mplane)
    profiles_length, profiles_dir = data[0], data[1] 
    # find maximums in profiles_length
    dirs = [] # list of dir with maximum length
    for i in range (len(profiles_dir)):
        dir = profiles_dir[i%len(profiles_dir)] 
        val = profiles_length[i%len(profiles_length)] 
        val_list = [val]
        for j in range(1,3,1):
            val_list.append(profiles_length[(i-j)%len(profiles_length)])
            val_list.append(profiles_length[(i+j)%len(profiles_length)])
        if val == max(val_list):
            dirs.append(dir)
    for i in range ( len(dirs)):
        dir = dirs[i]
        sys.stdout.write('%003d %02d %003d\n' \
          % (mplane.dir, abs(mplane.dip+90), dir ))
